import _regeneratorRuntime from "@babel/runtime/regenerator";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _isEqual from "lodash/isEqual";
import _map from "lodash/map";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";
import _isFunction from "lodash/isFunction";
var _excluded = ["lovCode", "options", "value", "textValue", "onFocus", "onChange", "valueField", "displayField", "lazyLoad"];

/**
 * index
 * 只用于表单内部
 * @date 2018/10/15

 */
import React from 'react';
import { Select } from 'antd';
import request from "../../utils/request";
import notification from "../../utils/notification";
import { getEnvConfig } from "../../utils/iocUtils";
import { getCurrentOrganizationId } from "../../utils/utils";

var _getEnvConfig = getEnvConfig(),
    CPAAS_PLATFORM = _getEnvConfig.CPAAS_PLATFORM;

function mapTo$Options(_ref) {
  var _ref$options = _ref.options,
      options = _ref$options === void 0 ? [] : _ref$options,
      _ref$valueField = _ref.valueField,
      valueField = _ref$valueField === void 0 ? 'valueField' : _ref$valueField,
      _ref$displayField = _ref.displayField,
      displayField = _ref$displayField === void 0 ? 'meaning' : _ref$displayField;
  return _map(options, function (opt) {
    return /*#__PURE__*/React.createElement(Select.Option, {
      key: opt[valueField],
      value: opt[valueField]
    }, opt[displayField]);
  });
}
/**
 * 获取 查询值集的方法
 * queryUrl 有值 返回方法 (params) => request(params)
 * 否则 返回 queryService
 * @param {string} queryUrl - 查询url
 * @param {function} queryService - 查询方法
 */


function getValueRequest(queryUrl, queryService) {
  if (queryUrl) {
    return function (params) {
      return request(queryUrl, {
        method: 'GET',
        query: params
      });
    };
  }

  return queryService;
}
/**
 * 统一查询独立、SQL、URL类型的值集
 * @param {Object} params - 额外的查询参数
 * @param {String} params.lovCode - 值集code
 */


function queryUnifyIdpValue() {
  return _queryUnifyIdpValue.apply(this, arguments);
} // /**
//  * 查询单个独立值集值
//  * @param {String} params.lovCode - 值集code
//  */
// async function queryIdpValue(params = {}) {
//   return request(`${CPAAS_PLATFORM}/v1/lovs/value`, {
//     query: params,
//   });
// }


function _queryUnifyIdpValue() {
  _queryUnifyIdpValue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var params,
        _args = arguments;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            params = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
            return _context.abrupt("return", request("".concat(CPAAS_PLATFORM, "/v1/lovs/data"), {
              method: 'GET',
              query: params
            }));

          case 2:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _queryUnifyIdpValue.apply(this, arguments);
}

var ValueList = /*#__PURE__*/function (_React$Component) {
  _inherits(ValueList, _React$Component);

  var _super = _createSuper(ValueList);

  function ValueList(props) {
    var _this;

    _classCallCheck(this, ValueList);

    _this = _super.call(this, props);
    _this.state = {// needLazyLoad: true, // 在检测到 更新属性变化后, 置为 true, 点击后变为 false
    };
    _this.handleSelectChange = _this.handleSelectChange.bind(_assertThisInitialized(_this));
    _this.handleFocus = _this.handleFocus.bind(_assertThisInitialized(_this)); // 处理查询值集的 结果

    _this.handleQueryOk = _this.handleQueryOk.bind(_assertThisInitialized(_this));
    _this.handleQueryError = _this.handleQueryError.bind(_assertThisInitialized(_this));
    _this.getTextField = _this.getTextField.bind(_assertThisInitialized(_this));
    _this.getTextValue = _this.getTextValue.bind(_assertThisInitialized(_this)); // 处理 options

    if (_isArray(props.options)) {
      var _this$props = _this.props,
          lovCode = _this$props.lovCode,
          queryUrl = _this$props.queryUrl,
          queryService = _this$props.queryService,
          _this$props$queryPara = _this$props.queryParams,
          queryParams = _this$props$queryPara === void 0 ? {} : _this$props$queryPara,
          options = _this$props.options,
          valueField = _this$props.valueField,
          displayField = _this$props.displayField;
      var nowParams = queryParams || {};

      if (_isFunction(queryParams)) {
        nowParams = queryParams();
      }

      if (lovCode) {
        nowParams.lovCode = lovCode;
      }

      _this.state = {
        $options: mapTo$Options({
          options: props.options,
          valueField: props.valueField,
          displayField: props.displayField
        }),
        shouldUpdateProps: {
          lovCode: lovCode,
          queryUrl: queryUrl,
          queryService: queryService,
          queryParams: nowParams,
          options: options,
          valueField: valueField,
          displayField: displayField
        }
      };
    }

    return _this;
  }

  _createClass(ValueList, [{
    key: "render",
    value: function render() {
      var _this$props2 = this.props,
          lovCode = _this$props2.lovCode,
          options = _this$props2.options,
          value = _this$props2.value,
          textValue = _this$props2.textValue,
          onFocus = _this$props2.onFocus,
          onChange = _this$props2.onChange,
          valueField = _this$props2.valueField,
          displayField = _this$props2.displayField,
          lazyLoad = _this$props2.lazyLoad,
          otherProps = _objectWithoutProperties(_this$props2, _excluded);

      var _this$state = this.state,
          $options = _this$state.$options,
          _this$state$needLazyL = _this$state.needLazyLoad,
          needLazyLoad = _this$state$needLazyL === void 0 ? true : _this$state$needLazyL;
      var selectProps = {
        onChange: this.handleSelectChange
      };

      if (lazyLoad && needLazyLoad) {
        selectProps.onFocus = this.handleFocus; //

        selectProps.value = $options ? value : this.getTextValue() || value;
      } else {
        selectProps.value = value;
      }

      return React.createElement(Select, _objectSpread(_objectSpread({}, otherProps), selectProps), $options);
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props3 = this.props,
          lazyLoad = _this$props3.lazyLoad,
          form = _this$props3.form,
          textField = _this$props3.textField,
          textValue = _this$props3.textValue;

      if (!lazyLoad) {
        this.handleDeal$Options();
      } else if (form && textField && this.getTextValue() && textValue) {
        // 设置表单值
        form.setFieldsValue(_defineProperty({}, this.getTextField(), textValue));
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      // 当 queryPrams 变动时,需要重新查询
      var _this$state2 = this.state,
          scu = _this$state2.shouldUpdateProps,
          _this$state2$needLazy = _this$state2.needLazyLoad,
          needLazyLoad = _this$state2$needLazy === void 0 ? true : _this$state2$needLazy;
      var _this$props4 = this.props,
          lovCode = _this$props4.lovCode,
          queryUrl = _this$props4.queryUrl,
          queryService = _this$props4.queryService,
          _this$props4$queryPar = _this$props4.queryParams,
          queryParams = _this$props4$queryPar === void 0 ? {} : _this$props4$queryPar,
          options = _this$props4.options,
          valueField = _this$props4.valueField,
          displayField = _this$props4.displayField,
          lazyLoad = _this$props4.lazyLoad;
      var nowParams = queryParams || {};

      if (_isFunction(queryParams)) {
        nowParams = queryParams();
      }

      if (lovCode) {
        nowParams.lovCode = lovCode;
      }

      var shouldUpdateProps = {
        lovCode: lovCode,
        queryUrl: queryUrl,
        queryService: queryService,
        queryParams: nowParams,
        options: options,
        valueField: valueField,
        displayField: displayField
      };

      if (lazyLoad && !needLazyLoad && !_isEqual(scu, shouldUpdateProps)) {
        // warn 如果更新了 更新条件 并且是懒加载, 则将需要懒加载设置为空
        // eslint-disable-next-line react/no-did-update-set-state
        this.setState({
          needLazyLoad: true
        });
      } else if (!lazyLoad && !_isEqual(scu, shouldUpdateProps)) {
        this.handleDeal$Options();
      }
    }
  }, {
    key: "handleQueryOk",
    value: function handleQueryOk(res) {
      var _this$props5 = this.props,
          lovCode = _this$props5.lovCode,
          queryUrl = _this$props5.queryUrl,
          queryService = _this$props5.queryService,
          _this$props5$queryPar = _this$props5.queryParams,
          queryParams = _this$props5$queryPar === void 0 ? {} : _this$props5$queryPar,
          options = _this$props5.options,
          valueField = _this$props5.valueField,
          displayField = _this$props5.displayField;
      var nowParams = queryParams || {};

      if (_isFunction(queryParams)) {
        nowParams = queryParams();
      }

      if (lovCode) {
        nowParams.lovCode = lovCode;
      }

      var $options;

      if (_isEmpty(res)) {
        $options = [];
      } else if (_isArray(res)) {
        // 没有分页的返回
        $options = mapTo$Options({
          options: res,
          valueField: valueField,
          displayField: displayField
        });
      } else if (res.failed) {
        // 出错
        notification.error({
          message: res.message
        });
      } else {
        // 有分页的返回
        $options = mapTo$Options({
          options: res.content,
          valueField: valueField,
          displayField: displayField
        });
      }

      this.setState({
        shouldUpdateProps: {
          lovCode: lovCode,
          queryUrl: queryUrl,
          queryService: queryService,
          queryParams: nowParams,
          options: options,
          valueField: valueField,
          displayField: displayField
        },
        $options: $options
      });
    }
  }, {
    key: "handleQueryError",
    value: function handleQueryError() {}
  }, {
    key: "handleDeal$Options",
    value: function handleDeal$Options() {
      var _this$props6 = this.props,
          lovCode = _this$props6.lovCode,
          queryUrl = _this$props6.queryUrl,
          queryService = _this$props6.queryService,
          _this$props6$queryPar = _this$props6.queryParams,
          queryParams = _this$props6$queryPar === void 0 ? {} : _this$props6$queryPar,
          options = _this$props6.options,
          valueField = _this$props6.valueField,
          displayField = _this$props6.displayField;
      var nowParams = queryParams || {};

      if (_isFunction(queryParams)) {
        nowParams = queryParams();
      }

      if (lovCode) {
        nowParams.lovCode = lovCode;
      }

      if (options) {
        // 直接有 options
        this.setState({
          $options: mapTo$Options({
            options: options,
            valueField: valueField,
            displayField: displayField
          }),
          shouldUpdateProps: {
            lovCode: lovCode,
            queryUrl: queryUrl,
            queryService: queryService,
            queryParams: nowParams,
            options: options,
            valueField: valueField,
            displayField: displayField
          }
        });
      } else {
        var rq = getValueRequest(queryUrl, queryService);

        if (!rq && lovCode) {
          // 查询 lov
          rq = queryUnifyIdpValue;
        }

        if (_isFunction(rq)) {
          rq(_objectSpread(_objectSpread({}, this.getTenantQueryParams()), nowParams)).then(this.handleQueryOk, this.handleQueryError);
        }
      }
    }
  }, {
    key: "handleFocus",
    value: function handleFocus() {
      var onFocus = this.props.onFocus;
      this.setState({
        needLazyLoad: false
      });
      this.handleDeal$Options();

      if (_isFunction(onFocus)) {
        onFocus.apply(void 0, arguments);
      }
    }
  }, {
    key: "handleSelectChange",
    value: function handleSelectChange(value, option) {
      var _this$props7 = this.props,
          onChange = _this$props7.onChange,
          form = _this$props7.form;

      if (_isFunction(onChange)) {
        onChange(value, option);
      }

      var textField = this.getTextField();

      if (form && textField) {
        // 通过 Option 的 children 拿到显示值
        form.setFieldsValue(_defineProperty({}, textField, option.props.children));
      }
    }
    /**
     * 获取 显示字段 对应的 后端存储数据
     */

  }, {
    key: "getTextField",
    value: function getTextField() {
      var _this$props8 = this.props,
          form = _this$props8.form,
          textField = _this$props8.textField;

      if (textField) {
        form.getFieldDecorator(textField);
      }

      return textField;
    }
    /**
     * 获取显示值
     */

  }, {
    key: "getTextValue",
    value: function getTextValue() {
      var _this$props9 = this.props,
          form = _this$props9.form,
          textField = _this$props9.textField,
          value = _this$props9.value,
          textValue = _this$props9.textValue;

      if (!value) {
        return;
      }

      var formTextValue;

      if (form && textField) {
        formTextValue = form.getFieldValue(textField);
      }

      if (value && formTextValue) {
        return formTextValue;
      }

      return textValue;
    }
  }, {
    key: "getTenantQueryParams",
    value: function getTenantQueryParams() {
      var organizationId = getCurrentOrganizationId();
      return {
        organizationId: organizationId,
        tenantId: organizationId
      };
    }
  }]);

  return ValueList;
}(React.Component);

ValueList.defaultProps = {
  valueField: 'value',
  displayField: 'meaning',
  // textField 将显示字段回写到表单中
  lazyLoad: true
};
export { ValueList as default };